<?php
/**
* Admin Grace Price Bands Controller
*
* This handles all AJAX requests from the Admin GUI Prices Section.
* These methods will create an AJAX response containing JSON data. The JSON
* data is read by the JS code and rendered into interface.
*
* @access 	public
* @author 	Rob, Valentin
* @copyright	ResMania 2009 all rights reserved.
* @version	1.0
* @link		http://developer.resmania.com/api
* @since  	05-2009
*/
class RM_Admin_GracePriceBandsController extends RM_Controller
{
    /* Database meta information */
    const F_ID = "id";
    
    /**
     * Returns JSON for the price bands notification list.
     */
    public function listJsonAction(){
        $model = new RM_GracePriceBands();
        $rows = $model->fetchAll()->toArray();
        return array(
            'data' => $rows
        );
    }
    /**
     * Update notification messages and enabled options
     * @return JSON object success
     */
    public function updatelistJsonAction()
    {
        $dataJson = $this->_getParam('data', '[]');
        $data = Zend_Json::decode($dataJson);

        $model = new RM_GracePriceBands();
        foreach ($data as $row){

            if ($row['id'] == 0) {
                unset($row['id']);
                $model->insert($row);
            } else {
                $dbRow = $model->find($row['id'])->current();
                if ($dbRow == null) continue;
                foreach ($row as $key => $value) {
                    $dbRow->$key = $value;
                }
                $dbRow->save();
            }
        }

        return array('data' => array('success' => true));
    }
    /**
     * Deletes a record from the model definition list
     */
    public function deleteJsonAction()
    {
        $ids = $this->_getParam('ids', array());
        $model = new RM_GracePriceBands();

        foreach ($ids as $id) {
            $row = $model->find($id)->current();
            if ($row === null) continue;
            $row->delete();
        }

        return array(
            'data' => array('success' => true)
        );
    }
    /**
     * @see modules/prices/js/config.js
     * @return 	json    json array information in format:
     * {fields: [{name: <name>, value: <value>, metainfo: <view metainfo>}]}
     */
    function configJsonAction()
    {
        $model = new RM_GracePriceBandsConfig();
        $fields = $model->fetchAll();
        $jsonFields = array();
        foreach ($fields as $field) {
            $jsonField = array();
            $jsonField[] = "name : '".$field->name."'";
            $jsonField[] = "value : '".$field->value."'";
            if ($field->metainfo != '') {
                $jsonField[] = 'metainfo : '.$field->metainfo;
            }
            $jsonFields[] = '{'.implode(',', $jsonField).'}';
        }

        return array(
            'data' => '{ fields: ['.implode(',', $jsonFields).'] }',
            'encoded' => true
        );
    }
    /**
     * @param   request pricebands_config  prices config information
     * @see modules/GracePriceBands/js/config.js
     * @return 	json    json array information: success or failure
     */
    function configupdateJsonAction()
    {
        $fields = $this->_getParam('pricebands_config', array());

        $model = new RM_GracePriceBandsConfig();
        foreach ($fields as $name => $value) {
            $configRow = $model->find($name)->current();
            $configRow->value = $value;
            $configRow->save();
        }

        return array('data' => array('success' => true));
    }
    /**     
     * @param   request id  unit id
     * @param   request unit_prices_config  unit price config information
     * @see modules/prices/js/unit_config.js
     * @return 	json    json array information: success or failure
     */
    function updateunitconfigJsonAction()
    {
        $unitID = $this->_getParam('id', '');
        $values = $this->_getParam('unit_grace_price_bands_config', array());

        $model = new RM_UnitGracePriceBandsConfig();
        $model->deleteByUnit($unitID);

        foreach ($values as $name => $value)
        {
            $row = array(
                'name' => $name,
                'value' => $value,
                'unit_id' => $unitID
            );

            $model->insert($row);
        }

        return array('data' => array('success' => true));
    }
    /**
     * @param   request id  unit id
     * @see modules/prices/js/unit_config.js
     * @return 	json    json array information in format:
     * {unit_id: <unit_id>, fields: [{name: <name>, value: <value>, metainfor: <metainfo>}]}
     */
    function unitconfigJsonAction()
    {
        $unitID = $this->_getParam('id', '');
        $model = new RM_UnitGracePriceBandsConfig();
        $fields = $model->fetchByUnit($unitID);

        foreach ($fields as $field) {
            $jsonField = array();
            $jsonField[] = "name : '".$field->name."'";
            $jsonField[] = "value : '".($field->unit_value !== null ? $field->unit_value : $field->default_value)."'";
            if ($field->metainfo != '') {
                $jsonField[] = 'metainfo : '.$field->metainfo;
            }
            $jsonFields[] = '{'.implode(',', $jsonField).'}';
        }

        return array(
            'data' => '{ unit_id: '.$unitID.', fields: ['.implode(',', $jsonFields).'] }',
            'encoded' => true
        );   
    }
    /**
     * @param   request unit_id  unit id
     * @param   request data  price rows information (if 'id'=0 this is a new row)
     * @see modules/prices/js/unit_list.js
     * @return 	json    json array information: success or failure
     */
    function updateJsonAction()
    {
        $unitID = $this->_getParam('unit_id');
        if ($unitID == null) {
            return array('data' => array('success' => 'false'));
        }
        $dataJson = $this->_getParam('data', '[]');
        $data = Zend_Json::decode($dataJson);
        $model = new RM_UnitGracePriceBands();
        foreach ($data as $row) {
            // maps the grid row to the database
            $dbRow = RM_UnitGracePriceBands::gridRowToDb($row);
            $dbRow['unit_id'] = $unitID;
            if ($dbRow['id'] == 0) {
                unset($dbRow['id']);
                $model->insert($dbRow);
            } else {
                $model->updateFromGUI($dbRow);
            }
        }
        return array('data' => array('success' => true));
    }
    /**
     * Returns JSON for the price bands units list.
     */
    public function unitlistJsonAction(){
        $unitID = $this->_getParam('id', '');
        $unitModel = new RM_Units;
        $unit = $unitModel->find($unitID)->current();
        // check if the data-based configuration is enabled for this unit
        $unitCfgModel = new RM_UnitGracePriceBandsConfig();
        $dateBased = $unitCfgModel->getDateBasedEnabled($unitID);
        // load the common fields
        $jsonFields = array();
        $rowModel = new RM_UnitGracePriceBandsModel();
        $rows = $rowModel->fetchAll(null, 'order');
        $name = null;
        foreach ($rows as $row){
            $name = $row->name;
            if ($row->admin_view!='' && (($dateBased==1) || !strcmp($name, self::F_ID))) {
                $jsonFields[] = $row->admin_view;
            }
        }
        // load the configured bands
        $pb = new RM_GracePriceBands();
        $rows = $pb->fetchAll(null, 'id');
        $fieldName = null;
        $fieldHeader = null;
        foreach ($rows as $row){
            $fieldName = "band_".$row->id;
            $fieldHeader = $row->name." (".$row->start_days."-".$row->end_days.")";
            $jsonFields[] = "{field: {id: \"$fieldName\", name: \"$fieldName\"}, column: { dataIndex: \"$fieldName\", header: \"$fieldHeader\", editor: new Ext.form.NumberField({allowBlank: false, allowDecimals: true, allowNegative: false})}}";
        }
        $json = "{
            fields : [".implode(',', $jsonFields)."]            
        }";
        return array(
            'data' => $json,
            'encoded' => true
        );
    }
    
    /**
     * Edit Price config for edit.js
     *
     * Copy information from database rm_daily_prices_config.admin_view_edit
     * for form inputs creation.
     *
     * @param   request start  offset for the SQL
     * @param   request limit  limit for the SQL
     * @param   request sort  sort for the SQL
     * @param   request dir  sorting direction for the SQL: ASC/DESC
     * @param   request id  unit id
     * @return 	array information in format:
     * {total: <total rows number>, data: [{<price_row>}, {<price_row>, ...}]}
     */
    function listpricesJsonAction()
    {
        // gets the request parameters
        $offset = $this->_getParam('start');
        $count = $this->_getParam('limit');
        $sort = $this->_getParam('sort', 'id');
        $direction = $this->_getParam('dir', 'DESC');
        $order = $sort . ' ' . $direction;
        $unitID = $this->_getParam('id', '');
        $unitModel = new RM_Units;
        $unit = $unitModel->find($unitID)->current();        
        // gets the pricing information for the currently configured bands
        $model = new RM_UnitGracePriceBands;
        $total = $model->getUnitCount($unit);
        $unitPrices = $model->getExpandedUnitPrices($unitID, $order, $count, $offset);
        $json = new stdClass;
        $json->total = $total;
        $json->data = $unitPrices;
        return array(
            'data' => $json
        );
    }
    /**
     * Deletes a line from the unit price definition list
     */
    public function unitdeleteJsonAction()
    {
        $ids = $this->_getParam('ids', array());
        $model = new RM_UnitGracePriceBands();
        foreach ($ids as $id) {
            // deletes this row
            $model->delete(self::F_ID."=$id");
        }
        return array(
            'data' => array('success' => true)
        );
    }
}
